package com.neuedu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neuedu.pojo.Mail;
import com.neuedu.pojo.User;
import com.neuedu.service.IMailService;
import com.neuedu.service.IUserService;
import com.neuedu.util.CommonResult;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;

@RestController
@RequestMapping("/mail")
public class MailController {
    @Resource
    JavaMailSender mailSender;
    @Resource
    IMailService mailService;
    @Resource
    IUserService userService;

    @PostMapping("/send")
    CommonResult handler(Mail mail) throws MessagingException, UnsupportedEncodingException {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(mail.getFrom(), mail.getPersonal());
        helper.setTo(mail.getTo());
        helper.setSubject(mail.getSubject());
        helper.setText(mail.getContent(), true);
        mailSender.send(message);
        return CommonResult.success("邮件发送成功");
    }

    @PostMapping("/sendSecurityCode")
    CommonResult sendSecurityCode(String username, String email) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);
        if (user == null) {
            return CommonResult.failed("用户不存在");
        } else if (user.getEmail().equals(email)) {
            if (mailService.sendSecurityCode(user.getUsername(), email)) {
                return CommonResult.success(null);
            } else {
                return CommonResult.failed("发送失败，请检查邮箱是否正确");
            }
        } else {
            return CommonResult.failed("邮箱错误");
        }
    }
}
